<?php


namespace app\agent\service;

class RechargeService
{
	public static function use_card($options)
	{
		\think\Db::startTrans();
		try {
			$card = \think\Db::name("app_agent_recharge_card")->where("card", $options["card"])->find();
			if (empty($card)) {
				return ["code" => \app\system\model\Code::error, "msg" => "卡密不存在"];
			}
			if ($card["status"] == 1) {
				return ["code" => \app\system\model\Code::error, "msg" => "卡密已使用"];
			}
			$agent = \think\Db::name("app_agent")->where("id", $options["agent_id"])->find();
			if ($card["type"] == 0) {
				\app\common\AppAgent::money($agent, $card["value"] + $card["give"], 0, "使用了充值卡:{$options["card"]} 卡的面值:{$card["value"]},赠送:{$card["give"]}");
			}
			\think\Db::name("app_agent_recharge_card")->where(["id" => $card["id"]])->update(["useuid" => $agent["id"], "usetime" => time(), "status" => 1]);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
	public static function recharge_money_order($options)
	{
		\think\Db::startTrans();
		try {
			$options_config = \app\common\server\ConfigServer::get("options");
			if (!empty($options_config["agent_recharge_money_limit_minimum"]) && $options["money"] < $options_config["agent_recharge_money_limit_minimum"]) {
				return ["code" => \app\system\model\Code::fail, "msg" => "最低充值金额不能低于" . $options_config["agent_recharge_money_limit_minimum"]];
			}
			$isSystemAuthUnpaid = isSystemAuthUnpaid();
			if ($isSystemAuthUnpaid && \think\Db::name("app_order")->where(["pay_status" => 1])->count() >= \app\common\model\FreeQuota::OrderPayQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,付款订单数量上限为" . \app\common\model\FreeQuota::OrderPayQuota . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			if ($isSystemAuthUnpaid && \think\Db::name("app_order")->count() >= \app\common\model\FreeQuota::OrderQuota) {
				return ["code" => \app\system\model\Code::fail, "msg" => "当前授权为基础版,订单数量上限为" . \app\common\model\FreeQuota::OrderQuota . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			$order_no = create_order_no();
			$order = ["order_no" => $order_no, "user" => $options["agent_id"], "type" => \app\common\model\BuyType::AgentRecharge, "goods_type" => 0, "goods_num" => 1, "goods_value" => $options["money"], "pay_type" => $options["pay_type"], "create_time" => time(), "price" => $options["money"]];
			$order_id = \think\Db::name("app_order")->insertGetId($order);
			$order["id"] = $order_id;
			$order["order_key"] = \app\common\service\AppCardBuy::getOrderKey($order);
			\think\Db::commit();
			return ["code" => \app\system\model\Code::success, "data" => $order];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\system\model\Code::error, "msg" => $e->getMessage()];
		}
	}
}